package com.party.util.easyexcel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * 分片监听器
 *
 * @author gcx
 * @date 2020/2/14
 */
public class PartitionDataListener<T> extends AnalysisEventListener<T> {
    private int size;
    private Consumer<List<T>> consumer;
    private List<T> buffer;

    public PartitionDataListener(int size, Consumer<List<T>> consumer) {
        buffer = new ArrayList<>(this.size = size);
        this.consumer = consumer;
    }

    @Override
    public void invoke(T data, AnalysisContext context) {
        buffer.add(data);
        if (buffer.size() >= size) {
            consumer.accept(buffer);
            buffer = new ArrayList<>(size);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (!buffer.isEmpty()) {
            consumer.accept(buffer);
        }
    }
}
